package back_database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JTable;

public class DBAccess {

	private static final String sDBDriver = "com.mysql.jdbc.Driver";
	private static final String sConnStr = "jdbc:odbc:myDB";
	static Statement stmt = null;

	private static final String url = "jdbc:mysql://127.0.0.1:3306/javashop";
	private static final String username = "root";
	private static final String password = "123";

	/**
	 * 加载数据库驱动程序，构造函数
	 */
	public DBAccess() {

	}

	/**
	 * 获得数据库连接操作
	 * 
	 * @return
	 * 
	 */
	public static Connection getConnection() { // 连接数据库
		Connection conn = null;
		try {
			Class.forName(sDBDriver); // 注册驱动
			conn = DriverManager.getConnection(url, username, password);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return conn;
	}

	/**
	 * 数据库查询操作 参数sql为要查询的SQL语句 成功返回结果集，否则返回NULL
	 * 
	 * @return ResultSet
	 */
	public ResultSet executeQuery(String sql) {
		Connection conn = null;

		try {
			conn = getConnection();

			if (stmt == null)
				stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);

			return rs;

		} catch (SQLException sqlexception) {
			System.err.println("查询失败： " + sqlexception.getMessage());
			return null;

		}
	}

}
